package com.oe.code.controller;

import com.oe.code.dao.LagouAuthCodeDao;
import com.oe.code.model.LagouAuthCode;
import com.oe.lang.build.ResponseBuilder;
import com.oe.lang.resp.LdmResponse;
import com.oe.mail.MailService;
import com.oe.mail.req.SendMailReq;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.Date;


@RestController
public class CodeController {

    @Reference(check = false)
    MailService mailService;

    @Autowired
    LagouAuthCodeDao lagouAuthCodeDao;



    @RequestMapping(value = "/api/code/send/{email}")
    public LdmResponse createCode(@PathVariable("email") String email){
        String code = (int)(Math.random()*1000000)+"";
        LagouAuthCode auth  = new LagouAuthCode();
        auth.setCode(code);
        auth.setEmail(email);
        auth.setCreatetime(new Date());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int minute=calendar.get(Calendar.MINUTE);
        calendar.set(Calendar.MINUTE,minute+1);
        auth.setExpiretime(calendar.getTime());
        lagouAuthCodeDao.save(auth);
        SendMailReq req = new SendMailReq();
        req.setCode(code);
        req.setEmail(email);
        mailService.sendMail(req);

        return  ResponseBuilder.buildResponse(true,"200","验证码已发至邮箱！",null);
    }


    @RequestMapping(value = "/api/code/check/{email}/{code}")
    public LdmResponse createCode(@PathVariable("email") String email, @PathVariable("code") String code){

        LagouAuthCode lagouAuthCode = lagouAuthCodeDao.selectOneByCodeAndAndEmail(code, email);
        if(lagouAuthCode==null){
            return ResponseBuilder.buildResponse(false,"500","验证码不正确！",null);
        }
        long currentTime = System.currentTimeMillis();
        long time = lagouAuthCode.getExpiretime().getTime();
        if(currentTime>time){
            return ResponseBuilder.buildResponse(false,"500","验证码已过期！",null);
        }
        return ResponseBuilder.buildResponse(true,"200",null,null);
    }
}
